Public Class DocumentControl
    Inherits System.Windows.Forms.UserControl

    Public Event DocumentSelected(ByVal DocumentPath As String, ByVal DocumentId As String, ByVal FolderId As String, ByVal DocumentName As String)
    Public Event DocumentSelectionCanceled()
    Private binding As SforceServiceWrapper = New SforceServiceWrapper(True, True)

#Region "Properties"
    Private _fileName As String = ""
    Private _documentID As String = ""
    Private _documentName As String = ""
    Private _folderID As String = ""
    Private _authMode As AUTHENTICATION_MODE
    Private _sessionId As String
    Private _serverURL As String
    Private _userId As String
    Private _mode As SHOW_MODE

    Public Enum SHOW_MODE
        OPEN_MODE
        SAVE_MODE
    End Enum
    Public Enum AUTHENTICATION_MODE
        SESSION_ID
        USER_CREDENTIALS
    End Enum

    Public Property Mode() As SHOW_MODE
        Get
            Return _mode
        End Get
        Set(ByVal Value As SHOW_MODE)
            txtFileName.Visible = (Value = SHOW_MODE.SAVE_MODE)
            txtFileName.Text = _documentName
            If (txtFileName.Visible) Then
                Me.btnOpen.Text = "Save"
            Else
                Me.btnOpen.Text = "Open"
            End If
            _mode = Value
        End Set
    End Property
    Public Property UserId() As String
        Get
            Return _userId
        End Get
        Set(ByVal Value As String)
            _userId = Value
        End Set
    End Property
    Public Property ServerURL() As String
        Get
            Return _serverURL
        End Get
        Set(ByVal Value As String)
            If Not Value Is Nothing Then
                binding.Url = Value.Replace("Soap/u/", "Soap/c/")
                _serverURL = Value
            End If
        End Set
    End Property
    Public Property SessionId() As String
        Get
            Return _sessionId
        End Get
        Set(ByVal Value As String)
            binding.SessionHeaderValue = New sforce.SessionHeader
            binding.SessionHeaderValue.sessionId = Value
            _sessionId = Value
        End Set
    End Property
    Public Property AuthenticationMode() As AUTHENTICATION_MODE
        Get
            Return _authMode
        End Get
        Set(ByVal Value As AUTHENTICATION_MODE)
            If Value = AUTHENTICATION_MODE.SESSION_ID Then
                Me.Panel1.Visible = False
            Else
                Me.Panel1.Visible = True
            End If
            _authMode = Value
        End Set
    End Property
    Public Property folderID() As String
        Get
            Return _folderID
        End Get
        Set(ByVal Value As String)
            _folderID = Value
        End Set
    End Property
    Public Property documentName() As String
        Get
            Return _documentName
        End Get
        Set(ByVal Value As String)
            _documentName = Value
        End Set
    End Property
    Public ReadOnly Property documentID() As String
        Get
            Return _documentID
        End Get
    End Property
    Public ReadOnly Property fileName() As String
        Get
            Return _fileName
        End Get
    End Property
#End Region

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        Me.AuthenticationMode = _authMode
    End Sub

    'UserControl1 overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents btnOpen As System.Windows.Forms.Button
    Friend WithEvents btnCancel As System.Windows.Forms.Button
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents btnLogin As System.Windows.Forms.Button
    Friend WithEvents txtPassword As System.Windows.Forms.TextBox
    Friend WithEvents txtUserName As System.Windows.Forms.TextBox
    Friend WithEvents ImageList1 As System.Windows.Forms.ImageList
    Friend WithEvents cboFolders As System.Windows.Forms.ComboBox
    Friend WithEvents Label4 As System.Windows.Forms.Label
    Friend WithEvents btnNewFolder As System.Windows.Forms.Button
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    Friend WithEvents ContextMenu1 As System.Windows.Forms.ContextMenu
    Friend WithEvents ToolBar1 As System.Windows.Forms.ToolBar
    Friend WithEvents ToolBarButton1 As System.Windows.Forms.ToolBarButton
    Friend WithEvents mnuIcons As System.Windows.Forms.MenuItem
    Friend WithEvents mnuList As System.Windows.Forms.MenuItem
    Friend WithEvents mnuDetails As System.Windows.Forms.MenuItem
    Friend WithEvents lvDocs As System.Windows.Forms.ListView
    Friend WithEvents ColumnHeader1 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader2 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader3 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader4 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader5 As System.Windows.Forms.ColumnHeader
    Friend WithEvents Panel2 As System.Windows.Forms.Panel
    Friend WithEvents ContextMenu2 As System.Windows.Forms.ContextMenu
    Friend WithEvents mnuDeleteDoc As System.Windows.Forms.MenuItem
    Friend WithEvents mnuRenameDoc As System.Windows.Forms.MenuItem
    Friend WithEvents txtFileName As System.Windows.Forms.TextBox
    Friend WithEvents Label1 As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(DocumentControl))
        Me.ImageList1 = New System.Windows.Forms.ImageList(Me.components)
        Me.btnOpen = New System.Windows.Forms.Button
        Me.btnCancel = New System.Windows.Forms.Button
        Me.Label3 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.btnLogin = New System.Windows.Forms.Button
        Me.txtPassword = New System.Windows.Forms.TextBox
        Me.txtUserName = New System.Windows.Forms.TextBox
        Me.cboFolders = New System.Windows.Forms.ComboBox
        Me.Label4 = New System.Windows.Forms.Label
        Me.btnNewFolder = New System.Windows.Forms.Button
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.ContextMenu1 = New System.Windows.Forms.ContextMenu
        Me.mnuIcons = New System.Windows.Forms.MenuItem
        Me.mnuList = New System.Windows.Forms.MenuItem
        Me.mnuDetails = New System.Windows.Forms.MenuItem
        Me.ToolBar1 = New System.Windows.Forms.ToolBar
        Me.ToolBarButton1 = New System.Windows.Forms.ToolBarButton
        Me.lvDocs = New System.Windows.Forms.ListView
        Me.ColumnHeader1 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader2 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader3 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader4 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader5 = New System.Windows.Forms.ColumnHeader
        Me.ContextMenu2 = New System.Windows.Forms.ContextMenu
        Me.mnuDeleteDoc = New System.Windows.Forms.MenuItem
        Me.mnuRenameDoc = New System.Windows.Forms.MenuItem
        Me.Panel2 = New System.Windows.Forms.Panel
        Me.txtFileName = New System.Windows.Forms.TextBox
        Me.Label1 = New System.Windows.Forms.Label
        Me.Panel1.SuspendLayout()
        Me.Panel2.SuspendLayout()
        Me.SuspendLayout()
        '
        'ImageList1
        '
        Me.ImageList1.ImageSize = New System.Drawing.Size(16, 16)
        Me.ImageList1.ImageStream = CType(resources.GetObject("ImageList1.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.ImageList1.TransparentColor = System.Drawing.Color.Transparent
        '
        'btnOpen
        '
        Me.btnOpen.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.btnOpen.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btnOpen.Location = New System.Drawing.Point(296, 306)
        Me.btnOpen.Name = "btnOpen"
        Me.btnOpen.Size = New System.Drawing.Size(72, 24)
        Me.btnOpen.TabIndex = 10
        Me.btnOpen.Text = "Open"
        '
        'btnCancel
        '
        Me.btnCancel.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btnCancel.Location = New System.Drawing.Point(378, 306)
        Me.btnCancel.Name = "btnCancel"
        Me.btnCancel.Size = New System.Drawing.Size(72, 24)
        Me.btnCancel.TabIndex = 9
        Me.btnCancel.Text = "Cancel"
        '
        'Label3
        '
        Me.Label3.Location = New System.Drawing.Point(184, 8)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(56, 16)
        Me.Label3.TabIndex = 16
        Me.Label3.Text = "Password:"
        '
        'Label2
        '
        Me.Label2.Location = New System.Drawing.Point(8, 8)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(64, 16)
        Me.Label2.TabIndex = 15
        Me.Label2.Text = "User name:"
        '
        'btnLogin
        '
        Me.btnLogin.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btnLogin.Location = New System.Drawing.Point(368, 12)
        Me.btnLogin.Name = "btnLogin"
        Me.btnLogin.Size = New System.Drawing.Size(48, 24)
        Me.btnLogin.TabIndex = 14
        Me.btnLogin.Text = "Login"
        '
        'txtPassword
        '
        Me.txtPassword.Location = New System.Drawing.Point(184, 24)
        Me.txtPassword.Name = "txtPassword"
        Me.txtPassword.PasswordChar = Microsoft.VisualBasic.ChrW(42)
        Me.txtPassword.Size = New System.Drawing.Size(160, 20)
        Me.txtPassword.TabIndex = 13
        Me.txtPassword.Text = "Hailey24"
        '
        'txtUserName
        '
        Me.txtUserName.Location = New System.Drawing.Point(8, 24)
        Me.txtUserName.Name = "txtUserName"
        Me.txtUserName.Size = New System.Drawing.Size(168, 20)
        Me.txtUserName.TabIndex = 12
        Me.txtUserName.Text = "mobile2@merce.com"
        '
        'cboFolders
        '
        Me.cboFolders.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.cboFolders.Location = New System.Drawing.Point(59, 12)
        Me.cboFolders.Name = "cboFolders"
        Me.cboFolders.Size = New System.Drawing.Size(184, 21)
        Me.cboFolders.Sorted = True
        Me.cboFolders.TabIndex = 17
        '
        'Label4
        '
        Me.Label4.Location = New System.Drawing.Point(3, 12)
        Me.Label4.Name = "Label4"
        Me.Label4.Size = New System.Drawing.Size(48, 16)
        Me.Label4.TabIndex = 18
        Me.Label4.Text = "Look in:"
        '
        'btnNewFolder
        '
        Me.btnNewFolder.Location = New System.Drawing.Point(259, 12)
        Me.btnNewFolder.Name = "btnNewFolder"
        Me.btnNewFolder.Size = New System.Drawing.Size(72, 24)
        Me.btnNewFolder.TabIndex = 19
        Me.btnNewFolder.Text = "New Folder"
        '
        'Panel1
        '
        Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Panel1.Controls.Add(Me.Label3)
        Me.Panel1.Controls.Add(Me.Label2)
        Me.Panel1.Controls.Add(Me.btnLogin)
        Me.Panel1.Controls.Add(Me.txtPassword)
        Me.Panel1.Controls.Add(Me.txtUserName)
        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Top
        Me.Panel1.DockPadding.All = 5
        Me.Panel1.Location = New System.Drawing.Point(5, 5)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(462, 56)
        Me.Panel1.TabIndex = 20
        '
        'ContextMenu1
        '
        Me.ContextMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuIcons, Me.mnuList, Me.mnuDetails})
        '
        'mnuIcons
        '
        Me.mnuIcons.Index = 0
        Me.mnuIcons.RadioCheck = True
        Me.mnuIcons.Text = "Icons"
        '
        'mnuList
        '
        Me.mnuList.Checked = True
        Me.mnuList.Index = 1
        Me.mnuList.RadioCheck = True
        Me.mnuList.Text = "List"
        '
        'mnuDetails
        '
        Me.mnuDetails.Index = 2
        Me.mnuDetails.RadioCheck = True
        Me.mnuDetails.Text = "Details"
        '
        'ToolBar1
        '
        Me.ToolBar1.Buttons.AddRange(New System.Windows.Forms.ToolBarButton() {Me.ToolBarButton1})
        Me.ToolBar1.ButtonSize = New System.Drawing.Size(16, 16)
        Me.ToolBar1.Divider = False
        Me.ToolBar1.Dock = System.Windows.Forms.DockStyle.None
        Me.ToolBar1.DropDownArrows = True
        Me.ToolBar1.ImageList = Me.ImageList1
        Me.ToolBar1.Location = New System.Drawing.Point(352, 8)
        Me.ToolBar1.Name = "ToolBar1"
        Me.ToolBar1.ShowToolTips = True
        Me.ToolBar1.Size = New System.Drawing.Size(40, 26)
        Me.ToolBar1.TabIndex = 21
        '
        'ToolBarButton1
        '
        Me.ToolBarButton1.DropDownMenu = Me.ContextMenu1
        Me.ToolBarButton1.ImageIndex = 2
        Me.ToolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton
        Me.ToolBarButton1.ToolTipText = "Views"
        '
        'lvDocs
        '
        Me.lvDocs.AllowDrop = True
        Me.lvDocs.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.lvDocs.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ColumnHeader1, Me.ColumnHeader2, Me.ColumnHeader3, Me.ColumnHeader4, Me.ColumnHeader5})
        Me.lvDocs.ContextMenu = Me.ContextMenu2
        Me.lvDocs.LargeImageList = Me.ImageList1
        Me.lvDocs.Location = New System.Drawing.Point(10, 51)
        Me.lvDocs.Name = "lvDocs"
        Me.lvDocs.Size = New System.Drawing.Size(440, 248)
        Me.lvDocs.SmallImageList = Me.ImageList1
        Me.lvDocs.TabIndex = 22
        Me.lvDocs.View = System.Windows.Forms.View.Details
        '
        'ColumnHeader1
        '
        Me.ColumnHeader1.Text = "Name"
        Me.ColumnHeader1.Width = 155
        '
        'ColumnHeader2
        '
        Me.ColumnHeader2.Text = "Type"
        Me.ColumnHeader2.Width = 70
        '
        'ColumnHeader3
        '
        Me.ColumnHeader3.Text = "Size"
        Me.ColumnHeader3.Width = 79
        '
        'ColumnHeader4
        '
        Me.ColumnHeader4.Text = "Date Modified"
        Me.ColumnHeader4.Width = 114
        '
        'ColumnHeader5
        '
        Me.ColumnHeader5.Text = "Date Created"
        Me.ColumnHeader5.Width = 147
        '
        'ContextMenu2
        '
        Me.ContextMenu2.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.mnuDeleteDoc, Me.mnuRenameDoc})
        '
        'mnuDeleteDoc
        '
        Me.mnuDeleteDoc.Index = 0
        Me.mnuDeleteDoc.Text = "Delete"
        '
        'mnuRenameDoc
        '
        Me.mnuRenameDoc.Index = 1
        Me.mnuRenameDoc.Text = "Rename"
        '
        'Panel2
        '
        Me.Panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Panel2.Controls.Add(Me.Label1)
        Me.Panel2.Controls.Add(Me.txtFileName)
        Me.Panel2.Controls.Add(Me.ToolBar1)
        Me.Panel2.Controls.Add(Me.Label4)
        Me.Panel2.Controls.Add(Me.lvDocs)
        Me.Panel2.Controls.Add(Me.btnNewFolder)
        Me.Panel2.Controls.Add(Me.cboFolders)
        Me.Panel2.Controls.Add(Me.btnOpen)
        Me.Panel2.Controls.Add(Me.btnCancel)
        Me.Panel2.Dock = System.Windows.Forms.DockStyle.Fill
        Me.Panel2.Location = New System.Drawing.Point(5, 61)
        Me.Panel2.Name = "Panel2"
        Me.Panel2.Size = New System.Drawing.Size(462, 342)
        Me.Panel2.TabIndex = 23
        '
        'txtFileName
        '
        Me.txtFileName.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.txtFileName.Location = New System.Drawing.Point(80, 308)
        Me.txtFileName.Name = "txtFileName"
        Me.txtFileName.Size = New System.Drawing.Size(200, 20)
        Me.txtFileName.TabIndex = 23
        Me.txtFileName.Text = ""
        '
        'Label1
        '
        Me.Label1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.Label1.Location = New System.Drawing.Point(8, 310)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(64, 16)
        Me.Label1.TabIndex = 24
        Me.Label1.Text = "File name:"
        '
        'DocumentControl
        '
        Me.Controls.Add(Me.Panel2)
        Me.Controls.Add(Me.Panel1)
        Me.DockPadding.All = 5
        Me.Name = "DocumentControl"
        Me.Size = New System.Drawing.Size(472, 408)
        Me.Panel1.ResumeLayout(False)
        Me.Panel2.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub LoadDocs(ByVal FolderID As String)

        Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
        Me.lvDocs.Items.Clear()

        Try
            Dim soql As String
            If FolderID = "" Then
                soql = "Select BodyLength, CreatedDate, Id, LastModifiedDate, Name, Type from Document where folderId = '" & UserId & "'"
            Else
                soql = "Select BodyLength, CreatedDate, Id, LastModifiedDate, Name, Type from Document  where folderId = '" & FolderID & "'"
            End If
            Dim qr As sforce.QueryResult = binding.query(soql)

            If qr.records Is Nothing Then
                Me.Cursor = Cursors.Default
                Return
            End If

            If qr.records.Length > 0 Then
                For i As Integer = 0 To qr.records.Length - 1
                    Dim doc As sforce.Document = CType(qr.records(i), sforce.Document)
                    Dim dnode As System.Windows.Forms.ListViewItem
                    If doc.Name = "" Then
                        dnode = New System.Windows.Forms.ListViewItem("no name", 2)
                    Else
                        dnode = New System.Windows.Forms.ListViewItem(doc.Name.Trim(), 2)
                    End If
                    dnode.Tag = doc
                    dnode.ImageIndex = 1
                    Me.lvDocs.Items.Add(dnode)
                    dnode.SubItems.Add(doc.Type)
                    dnode.SubItems.Add(FormatSize(CLng(doc.BodyLength)))
                    dnode.SubItems.Add(doc.LastModifiedDate.ToString())
                    dnode.SubItems.Add(doc.CreatedDate.ToString())
                Next
            End If
        Catch ex As Exception
            System.Diagnostics.Trace.WriteLine(ex.Message)
        End Try
        Me.Cursor = System.Windows.Forms.Cursors.Default
    End Sub
    Private Function FormatSize(ByVal size As Long) As String
        If size < 1000 Then
            Return "1 KB"
        ElseIf size < 1000000 Then
            Dim dsize As Double
            dsize = size / 1000
            Return Format(dsize, "#,### KB")
        Else
            Dim dsize As Double
            dsize = size / 1000000
            Return Format(dsize, "#,###.# MB")
        End If
    End Function
    Public Sub LoadFolders(Optional ByVal FolderId As String = "x")

        Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
        RemoveHandler cboFolders.SelectedIndexChanged, AddressOf cboFolders_SelectedIndexChanged
        'Application.DoEvents()
        Try
            Me.cboFolders.Items.Clear()
            'Check to see if this is the root (no id)
            'Add the Personal Folder item
            Me.cboFolders.Items.Add("My Personal Documents")
            Dim qr As sforce.QueryResult
            qr = binding.query("select name, id from folder where type = 'Document'")
            Dim SelectedIndex As Integer = 0
            If qr.records.Length > 0 Then
                For Each sobj As sforce.sObject In qr.records
                    Me.cboFolders.Items.Add(New ComboFolderItem(CType(sobj, sforce.Folder)))
                    If (FolderId.Equals(sobj.Id)) Then
                        SelectedIndex = Me.cboFolders.Items.Count - 1
                    End If
                Next
            End If

            AddHandler cboFolders.SelectedIndexChanged, AddressOf cboFolders_SelectedIndexChanged
            Me.cboFolders.SelectedIndex = SelectedIndex
        Catch ex As Exception
            System.Diagnostics.Trace.WriteLine(ex.Message)
        End Try
        Me.Cursor = System.Windows.Forms.Cursors.Default
    End Sub
    Private Function OpenDoc(ByVal DocID As String) As String

        Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
        Dim docs() As sforce.sObject = binding.retrieve("body, name, folderID", "Document", New String() {DocID})
        Dim fName As String = System.IO.Path.GetTempPath() & CType(docs(0), sforce.Document).Name
        Dim fs As System.IO.FileStream = New System.IO.FileStream(fName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
        fs.Write(CType(docs(0), sforce.Document).Body, 0, CType(docs(0), sforce.Document).Body.Length)
        fs.Flush()
        fs.Close()
        _documentID = DocID
        _documentName = CType(docs(0), sforce.Document).Name
        _folderID = CType(docs(0), sforce.Document).FolderId
        Me.Cursor = System.Windows.Forms.Cursors.Default
        Return fName

    End Function
    Private Sub GetSelectedDoc()
        Dim doc As sforce.Document = CType(lvDocs.SelectedItems(0).Tag, sforce.Document)
        _fileName = OpenDoc(doc.Id)
        _documentID = doc.Id
        _documentName = doc.Name
        If Me.cboFolders.SelectedItem.GetType().Equals(GetType(ComboFolderItem)) Then
            _folderID = CType(Me.cboFolders.SelectedItem, ComboFolderItem).Folder.Id
        Else
            _folderID = UserId
        End If
        RaiseEvent DocumentSelected(fileName, documentID, folderID, documentName)
    End Sub
    Private Sub lvDocs_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvDocs.DoubleClick
        If lvDocs.SelectedItems.Count > 0 Then
            GetSelectedDoc()
        End If
    End Sub
    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        If binding Is Nothing Then
            binding = New SforceServiceWrapper(True, True)
        End If
        Dim lr As sforce.LoginResult = binding.login(Me.txtUserName.Text, Me.txtPassword.Text)
        binding.SessionHeaderValue = New sforce.SessionHeader
        binding.SessionHeaderValue.sessionId = lr.sessionId
        binding.Url = lr.serverUrl
        Me.SessionId = lr.sessionId
        Me.ServerURL = lr.serverUrl
        Me.UserId = lr.userId
        _userId = lr.userId
        Me.lvDocs.Enabled = True
        Me.btnOpen.Enabled = True
        Me.cboFolders.Items.Clear()
        LoadFolders()
    End Sub
    Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
        If (btnOpen.Text.Equals("Open")) Then
            GetSelectedDoc()
        Else
            'SaveDocument()
            System.Windows.Forms.MessageBox.Show("Want to save the docuemnt.")
        End If
    End Sub
    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        RaiseEvent DocumentSelectionCanceled()
    End Sub
    Private Sub cboFolders_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboFolders.SelectedIndexChanged
        If cboFolders.SelectedItem.GetType.Equals(GetType(ComboFolderItem)) Then
            Dim cfi As ComboFolderItem = CType(cboFolders.SelectedItem, ComboFolderItem)
            LoadDocs(cfi.Folder.Id)
        Else
            LoadDocs("")
        End If
    End Sub
    Private Sub ChangeView(ByVal mnuItem As MenuItem)
        For i As Integer = 0 To Me.ContextMenu1.MenuItems.Count - 1
            Me.ContextMenu1.MenuItems.Item(i).Checked = False
        Next
        mnuItem.Checked = True
        Select Case mnuItem.Text
            Case "Icons"
                Me.lvDocs.View = View.SmallIcon
            Case "List"
                Me.lvDocs.View = View.List
            Case "Details"
                Me.lvDocs.View = View.Details
        End Select
    End Sub
    Private Sub mnuIcons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuIcons.Click
        ChangeView(mnuIcons)
    End Sub
    Private Sub mnuList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuList.Click
        ChangeView(mnuList)
    End Sub
    Private Sub mnuDetails_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDetails.Click
        ChangeView(mnuDetails)
    End Sub

    Private Sub btnNewFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewFolder.Click
        Dim f As New newFolder
        If f.ShowDialog() = DialogResult.OK Then
            Dim fldr As sforce.Folder = New sforce.Folder
            fldr.Name = f.txtFolderName.Text
            If f.ComboBox1.SelectedText = "Read Only" Then
                fldr.IsReadonly = True
                fldr.IsReadonlySpecified = True
            End If
            If f.rbHiddenAllUsers.Checked Then
                fldr.AccessType = "Hidden"
            Else
                fldr.AccessType = "Public"
            End If
            fldr.Type = "Document"
            Dim sr As sforce.SaveResult = binding.create(New sforce.sObject() {fldr})(0)
            If sr.success Then
                Me.LoadFolders()
            Else
                System.Windows.Forms.MessageBox.Show("There was an error during the creation of the new folder." + System.Environment.NewLine + System.Environment.NewLine + "Message: " + sr.errors(0).message, "Create Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        End If

    End Sub

    Private Sub lvDocs_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles lvDocs.DragEnter
        If Not Me.SessionId Is Nothing Then
            If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
                e.Effect = DragDropEffects.Copy
            Else
                e.Effect = DragDropEffects.None
            End If
        End If
    End Sub

    Private Sub lvDocs_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles lvDocs.DragDrop
        Try
            Dim a As Array = CType(e.Data.GetData(DataFormats.FileDrop), Array)

            If Not a Is Nothing Then
                For i As Integer = 0 To a.GetUpperBound(0)
                    Dim s As String = a.GetValue(i).ToString()
                    CreateDocument(s)
                Next
            End If
        Catch ex As Exception
            Trace.WriteLine("Error in DragDrop function: " + ex.Message)

            '// don't show MessageBox here - Explorer is waiting !
        End Try

    End Sub
    Private Sub CreateDocument(ByVal docPath As String)
        Dim doc As New sforce.Document
        Dim fi As System.IO.FileInfo = New System.IO.FileInfo(docPath)
        If fi.Length > 5000000 Then
            System.Windows.Forms.MessageBox.Show("This file is too big.  The maximum document size is 5 MB.", "Document Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            doc.Name = fi.Name
            doc.Description = fi.FullName
            doc.FolderId = CType(Me.cboFolders.SelectedItem, ComboFolderItem).Folder.Id
            Dim fs As System.IO.FileStream = System.IO.File.OpenRead(docPath)
            Dim buffer() As Byte
            ReDim buffer(Convert.ToInt32(fi.Length))
            fs.Read(buffer, 0, buffer.Length)
            doc.Body = buffer
            fs.Close()

            Dim qr As sforce.QueryResult = binding.query("select Id From Document where name = '" + doc.Name + "' and FolderId = '" + doc.FolderId + "'")
            Dim sr As sforce.SaveResult
            Dim answer As DialogResult = DialogResult.Yes
            Dim op As String = "create"
            If (qr.size > 0) Then
                answer = System.Windows.Forms.MessageBox.Show("The document " + doc.Name + " alread exists, do you want to replace it?", "Overwrite Document", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
                If (answer = DialogResult.Cancel) Then
                    Return
                ElseIf answer = DialogResult.Yes Then
                    op = "update"
                    doc.Id = qr.records(0).Id
                End If
            End If
            If (op = "update") Then
                sr = binding.update(New sforce.sObject() {doc})(0)
            Else
                sr = binding.create(New sforce.sObject() {doc})(0)
            End If
            If sr.success Then
                Me.LoadDocs(doc.FolderId)
            Else
                MessageBox.Show("There was an error creating the document." & System.Environment.NewLine + System.Environment.NewLine + "Message: " + sr.errors(0).message)
            End If
        End If

    End Sub

    Private Sub lvDocs_ItemDrag(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemDragEventArgs) Handles lvDocs.ItemDrag
        Try
            Trace.WriteLine(e.Item.GetType().ToString())
            Dim dobj As DataObject = New DataObject
            Dim fileNames() As String
            ReDim fileNames(lvDocs.SelectedItems.Count - 1)
            For i As Integer = 0 To fileNames.GetUpperBound(0)
                fileNames(i) = System.IO.Path.GetTempPath() & CType(CType(lvDocs.SelectedItems(i), ListViewItem).Tag, sforce.Document).Name
            Next
            dobj.SetData(DataFormats.FileDrop, fileNames)
            lvDocs.DoDragDrop(dobj, DragDropEffects.Copy)
        Catch ex As Exception
            Trace.WriteLine("ItemDrag:::" + ex.Message)
        End Try
    End Sub

    Private Sub lvDocs_QueryContinueDrag(ByVal sender As Object, ByVal e As System.Windows.Forms.QueryContinueDragEventArgs) Handles lvDocs.QueryContinueDrag
        If (e.Action = DragAction.Drop) Then
            For i As Integer = 0 To lvDocs.SelectedItems.Count - 1
                OpenDoc(CType(lvDocs.SelectedItems(i).Tag, sforce.Document).Id)
            Next
        End If
    End Sub

    Private Sub mnuDeleteDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDeleteDoc.Click
        If Me.lvDocs.SelectedItems.Count > 0 Then
            Dim strMsg As String
            If Me.lvDocs.SelectedItems.Count > 1 Then
                strMsg = "Are you sure you want to permanently delete multiple documents?"
            Else
                strMsg = "Are you sure you want to permanently delete " + CType(lvDocs.SelectedItems(0).Tag, sforce.Document).Name + "?"
            End If
            If MessageBox.Show(strMsg, "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                Dim ids() As String
                ReDim ids(lvDocs.SelectedItems.Count - 1)
                For i As Integer = 0 To ids.GetUpperBound(0)
                    ids(i) = CType(lvDocs.SelectedItems(i).Tag, sforce.Document).Id
                Next
                binding.delete(ids)
                LoadDocs(CType(Me.cboFolders.SelectedItem, ComboFolderItem).Folder.Id)
            End If
        End If
    End Sub

    Private Sub mnuRenameDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRenameDoc.Click
        Me.lvDocs.LabelEdit = True
        Me.lvDocs.SelectedItems(0).BeginEdit()
    End Sub

    Private Sub lvDocs_AfterLabelEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.LabelEditEventArgs) Handles lvDocs.AfterLabelEdit
        Try
            Dim doc As sforce.Document = CType(lvDocs.SelectedItems(0).Tag, sforce.Document)
            Dim newName As String = e.Label
            If Not newName.EndsWith(doc.Type) Then
                newName = newName & "." & doc.Type
            End If
            Dim updateDoc As sforce.Document = New sforce.Document
            updateDoc.Name = newName
            updateDoc.Id = doc.Id
            Dim sr As sforce.SaveResult = binding.update(New sforce.sObject() {updateDoc})(0)
            If Not sr.success Then
                MessageBox.Show("Could not rename the document." + vbCrLf & vbCrLf + "Message: " + sr.errors(0).message, "Rename Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else
                CType(lvDocs.SelectedItems(0).Tag, sforce.Document).Name = newName
            End If
            lvDocs.LabelEdit = False
        Catch ex As Exception
            MessageBox.Show("Error on rename." + vbCrLf + vbCrLf + "Message: " + ex.Message, "Rename Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class
